<%@ page import="com.example.dao.UserDao" %>
<%@ page import="com.example.domain.User" %>
<%@ page import="java.util.List" %>
<%@ page import="com.example.util.DBUtil" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
    <title>用户列表</title>
    <%@ include file="header.jsp" %>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>用户列表</h1>
        <a href="user_add.jsp" class="btn">+ 添加用户</a>
    </div>
    
    <% 
        String message = (String) session.getAttribute("message");
        String messageType = (String) session.getAttribute("messageType");
        if (message != null) {
    %>
        <div class="alert alert-<%= messageType %>"><%= message %></div>
    <%
            session.removeAttribute("message");
            session.removeAttribute("messageType");
        }
    %>
    
    <table>
        <thead>
            <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>真实姓名</th>
                <th>邮箱</th>
                <th>电话</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <% 
                try {
                    UserDao userDao = new UserDao(DBUtil.getConnection());
                    List<User> list = userDao.getAllUsers();
                    if (list.isEmpty()) {
            %>
                <tr>
                    <td colspan="6" style="text-align: center;">暂无用户数据</td>
                </tr>
            <%
                    } else {
                        for(User user : list){
            %>
                <tr>
                    <td><%= user.getId() %></td>
                    <td><%= user.getUsername() %></td>
                    <td><%= user.getRealname() != null ? user.getRealname() : "-" %></td>
                    <td><%= user.getEmail() != null ? user.getEmail() : "-" %></td>
                    <td><%= user.getPhone() != null ? user.getPhone() : "-" %></td>
                    <td class="actions">
                        <a href="user_edit.jsp?id=<%= user.getId() %>" class="btn">编辑</a>
                        <a href="user_delete.jsp?id=<%= user.getId() %>" class="btn btn-danger" 
                           onclick="return confirm('确定要删除用户 <%= user.getUsername() %> 吗？')">删除</a>
                    </td>
                </tr>
            <%
                        }
                    }
                } catch (Exception e) {
            %>
                <tr>
                    <td colspan="6" style="text-align: center; color: red;">
                        数据加载失败：<%= e.getMessage() %>
                    </td>
                </tr>
            <%
                }
            %>
        </tbody>
    </table>
</div>
</body>
</html>